﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Entities;
using Lion.WeiXin.Core.Data;
using System.Diagnostics;
namespace Lion.WeiXin
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class WeChatFilterAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();//开始计时
            AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
            watch.Stop();
            LogHelper.Info("获取访问access_token,耗时:");
            CostTime(watch.Elapsed);
            watch.Restart();//开始计时
            //当前Openid为空发起OAuth2 微信验证
            if(string.IsNullOrEmpty(CurrentUser.OpenId))
            {
                //获取微信验证回传code 值，如果值为空，说明需要进行第一步，发起验证
                string wcCode = filterContext.HttpContext.Request.QueryString["code"];
                if (string.IsNullOrEmpty(wcCode))
                {
                    //去微信验证
                    string returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri;
                    string weiXinUrl = OAuth.GetAuthorizeUrl(Config.AppId, returnUrl, "", OAuthScope.snsapi_base);
                    RedirectResult goUrl = new RedirectResult(weiXinUrl);
                    filterContext.Result = goUrl;
                }
                else
                {
                    //微信回传code后，通过此code 获取授权的access_token
                    OAuthAccessTokenResult auResult = OAuth.GetAccessToken(Config.AppId, Config.AppSecret, wcCode);
                    CurrentUser.OpenId = auResult.openid;
                    IWeChatUser iwcUser = new WeChatUserDAO();
                    WeChatUserModel wcUser = iwcUser.GetModel(CurrentUser.OpenId);
                    CurrentUser.WXUser = wcUser;
                }
            }
            watch.Stop();
            LogHelper.Info("OAuth2 验证,耗时:");
            CostTime(watch.Elapsed);
        }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null)
            {

                LogHelper.Error(filterContext.Exception, "出错了!");
                filterContext.ExceptionHandled = true;
               // ContentResult cr= new ContentResult();
                JsonResult errJson = new JsonResult();
                errJson.Data = new { code = "NO", msg = "出现一个错误，请稍后重试!" };
                errJson.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                //cr.Content = "出现一个错误！我已经处理了";
                filterContext.Result = errJson;
            }
        }

        /// <summary>
        /// 计算时间耗费
        /// </summary>
        /// <param name="ts"></param>
        public void CostTime(TimeSpan ts)
        {
            string timeInfo = string.Format("[{0}].总耗时{1:00}时{2:00}分{3:00}秒{4:00}毫秒 ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            //日志打印时间耗费
            LogHelper.Info(timeInfo);

        }
       
    }
}